<template>
    <div class="workInfo">
        <!-- 顶部 -->
        <div class="top">
            <div class="callback" @click="$router.back()">
                <img src="@/assets/callback.png" alt="">
            </div>
            <div class="top-title">
                {{ titleName }}
            </div>
        </div>
        <!-- 表单 -->
        <van-form @submit="doSubmit">
            <!-- 工作 -->
            <!-- <div class="work">
                <van-field :rules="[{ required: true, message: 'This option cannot be empty' }]" v-model="work.fieldValue"
                    is-link readonly label="Occupation" placeholder="Please select the Occupation"
                    @click="work.show = true" />
                <van-popup :rules="[{ required: true, message: 'This option cannot be empty' }]" v-model="work.show" round
                    position="bottom">
                    <van-cascader v-model="work.cascader" title="Please select the region" :options="work.list"
                        placeholder="Please select" @close="work.show = false" @finish="workFinish"
                        :field-names="{ text: 'name', value: 'id', children: 'children' }" />
                </van-popup>
            </div> -->
            <!-- 表单解构 -->
            <div v-for="item in formList" :key="item.id">
                <van-field v-if="item.type === 'text'" :rules="[{ required: true, message: 'This option cannot be empty' }]"
                    v-model="form.model.submitData[item.id]" :name="item.name" :label="item.name"
                    :placeholder="`Please enter ${item.name}`" />
                <van-field v-else-if="item.type === 'number'"
                    :rules="[{ required: true, message: 'This option cannot be empty' }]"
                    v-model.number="form.model.submitData[item.id]" :name="item.name" :label="item.name"
                    :placeholder="`Please enter ${item.name}`" />
                <!-- 工作类型 -->
                <div v-else-if="item.type === 'jobType'">
                    <van-field :rules="[{ required: true, message: 'This option cannot be empty' }]" v-model="fieldValue"
                        is-link readonly label="Occupation" :placeholder="`Please select the ${item.name}`"
                        @click="show = true" />
                    <van-popup :rules="[{ required: true, message: 'This option cannot be empty' }]" v-model="show" round
                        position="bottom">
                        <van-cascader v-model="cascader" title="Please select the region" :options="list"
                            placeholder="Please select" @close="show = false" @finish="Finish"
                            :field-names="{ text: 'name', value: 'id', children: 'children' }" />
                    </van-popup>
                </div>
                <!-- 住址类型 -->
                <div v-else-if="item.type === 'addressType'">
                    <div class="gsaddress">
                        <van-field :rules="[{ required: true, message: 'This option cannot be empty' }]"
                            v-model="address.fieldValue" is-link readonly :label="item.name"
                            placeholder="Please select the Company Address" @click="address.show = true" />
                        <van-popup v-model="address.show" round position="bottom">
                            <van-cascader v-model="address.cascader" title="Please select the region"
                                :options="address.list" placeholder="Please select" @close="address.show = false"
                                @finish="(event) => { addressFinish(event, item.id) }"
                                :field-names="{ text: 'name', value: 'id' }" @change="addressChange" />
                        </van-popup>
                    </div>
                </div>
                <!-- 详细地址 -->
                <div v-else-if="item.id === 'address.detailAddress'">
                    <van-field :rules="[{ required: true, message: 'The information cannot be empty' }]"
                        v-model="form.model.submitData[item.id]" :name="item.name" :label="item.name"
                        placeholder="Please enter the detailed address" />
                </div>
                <!-- 选择框 -->
                <div v-if="item.type === 'select'">
                    <van-field readonly clickable :name="item.name" v-model="form.model.submitData[item.id]" :value="value"
                        :label="item.name" :placeholder="`Please select ${item.name}`" @click="doClick(item)"
                        :rules="[{ required: true, message: 'The information cannot be empty' }]" />
                    <van-popup v-model="showPicker" position="bottom">
                        <van-picker show-toolbar :columns="columns" @confirm="Confirm" confirm-button-text="Confirm"
                            cancel-button-text="Cancel" @cancel="showPicker = false" />
                    </van-popup>
                </div>
                <!-- 联系人 -->
                <div v-for="ele in listdata" :key="ele.id" class="list" v-if="item.type === 'contact'">
                    <div class="title">{{ ele.mes }}</div>
                    <van-field v-model="form.model.submitData.userEmergs[ele.id].name" name="用户名" label="name"
                        placeholder="Please enter your name"
                        :rules="[{ required: true, message: 'Please enter your name' }]" />
                    <van-field v-model="form.model.submitData.userEmergs[ele.id].phone" name="phone" label="phone"
                        placeholder="Please fill in the phone number"
                        :rules="[{ required: true, message: 'Please fill in the phone number' }, {}]" />
                    <!-- 选择关系 -->
                    <van-field :rules="[{ required: true, message: 'Please select your relationship with the contact' }]"
                        readonly clickable name="relation" v-model="form.model.submitData.userEmergs[ele.id].relation"
                        :value="value" label="relation" placeholder="Please select your relationship with the contact"
                        @click="showPicker = true; index = ele.id" />
                    <van-popup v-model="showPicker" position="bottom">
                        <van-picker confirm-button-text="Confirm" cancel-button-text="Cancel" show-toolbar :columns="gxlist"
                            @confirm="doConfirm" @cancel="showPicker = false" />
                    </van-popup>
                </div>
            </div>
            <!-- 提交按钮 -->
            <van-button class="formBtn" type="button">Submit</van-button>
        </van-form>
    </div>
</template>

<script>
import { getJobInfomation, getwwcform, getAddressAPI, uploadbaseform, getdefaultform, getdevinceInfo } from "../../api/index.js";
import { jiami, jiemi } from "../../utils/aeskey.js";
import { Toast } from 'vant'
export default {
    name: 'workInfo',
    data() {
        return {
            a: '',
            titleName: '',
            detailAddress: '',
            show: false,
            fieldValue: '',
            list: [],
            cascader: '',
            //表单list
            formList: [],
            form: {
                model: {
                    formId: "",//表单id
                    submitData: {
                        professionInfo: {
                            workType: null,
                            profession: null
                        },
                        address: {
                            bigAddress: {
                                province: null,
                                city: null
                            },
                            detailAddress: null
                        },
                        companyAddress: {
                            bigAddress: {
                                province: null,
                                city: null
                            },
                            detailAddress: null
                        }
                    }
                },
            },

            listdata: [
                { id: 0, mes: 'Emergency contact 1' },
                { id: 1, mes: 'Emergency contact 2' },
                { id: 2, mes: 'Emergency contact 3' }
            ],
            type: {
                text: 'name',
                value: 'id',
                children: 'children'
            },
            address: {
                fieldValue: '',
                show: false,
                cascader: '',
                list: []
            },
            value: '',
            showPicker: false,
            columns: [],
            //关系列表
            gxlist: []
        }
    },
    methods: {
        // 当工作选完成时
        Finish({ selectedOptions }) {
            this.show = false
            console.log('selectedOptions', selectedOptions)
            this.fieldValue = selectedOptions.map((option) => option.name).join('/');
            const arr = selectedOptions.map((option) => option.id).join('/').split('/');
            try {
                this.form.model.submitData.professionInfo.workType = arr[0]
                this.form.model.submitData.professionInfo.profession = arr[1]
            } catch (error) {

            }
        },
        //获取工作信息
        async getworkinfo() {
            const res = await getJobInfomation()
            console.log('工作信息', jiemi(res.data))
            this.list = jiemi(res.data).model
        },
        //获取地址信息
        async getaddress() {
            const r = {
                model: ''
            }
            const res = await getAddressAPI(jiami(r))
            jiemi(res.data).model.forEach(item => {
                this.address.list.push({
                    id: item.id,
                    name: item.name,
                    children: item.children || null
                })
            })
            console.log(this.address.list, '省')
            console.log('地址信息', jiemi(res.data))
        },
        //当地址信息变化时
        async addressChange({ value, selectedOptions, tabIndex }) {
            const r = {
                model: value
            }
            const res = await getAddressAPI(jiami(r))
            console.log('市', jiemi(res.data))
            console.log('value, selectedOptions, tabIndex', value, selectedOptions, tabIndex)
            selectedOptions.forEach(item => {
                if (item.id === value) {
                    item.children = jiemi(res.data).model
                }
            })
            console.log('地址数据', this.address.list)
        },
        //当关系选择完毕时执行
        doConfirm(ele, value) {
            this.form.model.submitData.userEmergs[this.index].relation = ele
            this.showPicker = false
        },
        //公司地址选完市触发
        addressFinish({ selectedOptions }, id) {
            selectedOptions.forEach(item => {
                if (item.children) {
                    this.address.show = false
                }
            })
            this.address.fieldValue = selectedOptions.map((option) => option.name).join('/');
            try {
                let value = { province: selectedOptions[0].id || '', city: selectedOptions[1].id || '' };
                onChange(id, value)
            } catch (error) {
                console.log(error)
            }

        },
        onChange(key, value) {
            if (key.indexOf(".") > -1) {
                let strs = key.split(".");
                let m1 = this.form.model.submitData[strs[0]];
                if (m1 == null) {
                    m1 = {};
                }
                m1[strs[1]] = value;
                this.form.model.submitData[strs[0]] = m1;
            }
        },
        //提交按钮
        async doSubmit() {
            for (let k in this.formList) {
                let item = this.formList[k];
                this.onChange(item.id, this.form.model.submitData[item.id])
            }
            const formData = this.$store.state.formData
            const arr = formData.filter(item => item['formName'] === this.titleName)
            debugger
            this.form.model.formId = formData[0].formId || ''
            const res = await uploadbaseform(jiami(this.form))
            if (!res) return
            const result = jiemi(res.data)
            console.log(result, 'result')
            // console.log(jiemi(res))

            console.log(this.form, '表单')
            console.log(this.fieldValue, 'filedValue')
            Toast('Submitted successfully')
            await this.$store.dispatch('weiwancehngform')
            this.getForm()
            // this.getForm()
            this.toform()
            // this.$router.push('/personInformation')
            window.scrollTo({
                top: 0,
                behavior: "smooth"
            });
        },
        //获取指定表单
        async getForm() {
            const f = {
                model: {
                    formId: '',
                    nodeType: ''
                }
            }
            f.model.formId = this.$store.state.formData[0].formId || ''
            const res = await getdefaultform(jiami(f))
            console.log(res)
            console.log('工作指定表单', jiemi(res.data))
            this.formList = jiemi(res.data).model.forms[0].content

            let submitData = jiemi(res.data).model.baseInfo || {};

            let item = this.formList.filter(item => item.type == "contact")[0];
            if (item) {
                submitData.userEmergs = [
                    {},
                    {},
                    {},
                ]
            }
            if (!submitData.professionInfo) {
                submitData.professionInfo = this.form.model.submitData.professionInfo;
            }
            if (!submitData.address) {
                submitData.address = this.form.model.submitData.address;
            }
            if (!submitData.companyAddress) {
                submitData.companyAddress = this.form.model.submitData.companyAddress;
            }
            this.form.model.submitData = submitData;
            try {
                this.gxlist = jiemi(res.data).model.forms[0].content[0].props.relationList.map(item => item.id)
            } catch (error) {

            }
            console.log(jiemi(res.data), ']]]]]]]]]]]]]]]]]')
            console.log('表单list', this.formList)
        },
        //点击文本框触发
        doClick(item) {
            this.showPicker = true
            this.columns = item.options.map(item => item.id)
            console.log(this.columns)
            this.i = item
            console.log(this.i, 'i')
        },
        //点击确认按钮之后
        Confirm(value, index) {
            this.showPicker = false
            console.log(this.i, '------')
            this.form.model.submitData[this.i.id] = value
        },
        //获取地址信息
        async getaddress() {
            const r = {
                model: ''
            }
            const res = await getAddressAPI(jiami(r))
            jiemi(res.data).model.forEach(item => {
                this.address.list.push({
                    id: item.id,
                    name: item.name,
                    children: item.children || null
                })
            })
            console.log(this.address.list, '省')
            console.log('地址信息', jiemi(res.data))

        },
        //判断表单跳转哪里
        toform() {
            this.$store.dispatch('weiwancehngform')
            const form = this.$store.state.formData
            let item = {};
            for (var i in form) {
                item = form[i] || {};
                break;
            }
            console.log(form, 'form')
            console.log(item, 'item')
            if (item.formType == "OCR") {
                this.$router.push('/smrz')
                //跳转OCR
                return;
            } else if (item.formType == "ALIVE") {
                this.$router.push('/huoti')
                return
            } else if (item.formType == "BASIC") {
                // this.$router.push('/workInfo')
                //条表单
                return
            }
        },
    },
    async created() {
        //标题
        this.titleName = this.$store.state.formData[0].formName || ''
        this.$store.dispatch('weiwancehngform')
        this.getworkinfo()
        //获取地址信息
        this.getaddress()
        //获取指定表单
        this.getForm()
        console.log(this.form.model.submitData.userEmergs, 'user')

        const res = await getdevinceInfo()
        console.log(jiemi(res.data).list, '设备信息')

    }
}
</script>
<style lang="less" scoped>
@a: 3.75vw;

html,
body {
    scroll-behavior: smooth;
}

.workInfo {
    width: 100vw;
    height: (667/@a);
    background-color: #f5f5f5;
    padding-top: (67/@a);
    box-sizing: border-box;

    .top {
        height: (56/@a);
        background-color: #fff;
        width: 100vw;
        display: flex;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 99;

        .callback {
            margin-top: (20/@a);
            margin-left: (15/@a);
            width: (10/@a);

            img {
                width: 100%;
            }
        }

        .top-title {
            margin-left: (100/@a);
            margin-top: (17/@a);
            font-family: 'Inter';
            font-style: normal;
            font-weight: 400;
            font-size: (18/@a);
            color: #202020;
        }
    }

    .formBtn {
        width: (232/@a);
        height: (44/@a);
        background: linear-gradient(90deg, #8042FF 0%, #BC37FF 100%);
        border-radius: (10/@a);
        margin-top: (20/@a);
        margin-left: (70/@a);
    }
}
</style>